<?php

namespace App\Admin\Controller\Base;

use App\AbstractController;
use App\Common\Exception\ApiMessageException;
use App\Common\Util\AdminAuth;
use App\Common\Util\Response;
use Psr\Http\Message\ResponseInterface;
use think\annotation\route\Group;
use think\annotation\route\Route;

/**
 * 修改密码
 *
 * Class UpdatePasswordController
 */
class UpdatePasswordController extends AbstractController
{
    /**
     * 修改密码
     *
     * @return \think\Response
     * @throws ApiMessageException
     */
    public function updatePassword(): \think\Response
    {
        $user = AdminAuth::getInfo();

        if ($this->request->post('new') !== $this->request->post('new_confirm')) {
            throw new ApiMessageException('新密码和确认密码不一致');
        }

        if ($this->request->post('new') === $this->request->post('old')) {
            throw new ApiMessageException('新密码和原密码一致');
        }

        if (!preg_match('/^.{6,16}$/', $this->request->post('new'))) {
            throw new ApiMessageException('密码长度为6 - 16位');
        }

        if (!password_verify($this->request->post('old'), $user->password)) {
            throw new ApiMessageException('原密码错误');
        }

        $user->password = password_hash($this->request->post('new'), PASSWORD_DEFAULT);
        $user->save();

        return Response::json()->success();
    }
}